package cn.zswltech.gruul.xxljob;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.zswltech.gruul.common.dal.dao.OrgDOMapper;
import cn.zswltech.gruul.common.entity.OrgDO;
import cn.zswltech.gruul.common.util.SpringBeanUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.Sqls;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jim
 * @version 1.0.0
 * @descripition:
 * @date 2024/2/21 17:05
 */
@Slf4j
public class YunHuOrgFeatureTask implements Runnable{

    private final List<YunHuOrg> yunHuOrgList;

    public YunHuOrgFeatureTask(List<YunHuOrg> yunHuOrgList) {
        this.yunHuOrgList = yunHuOrgList;
    }

    @Override
    public void run() {
        log.info("开始同步云湖机构数据，机构数据列表：{}",yunHuOrgList.size());
        List<YunHuOrg> needUpdateOrgs;
        try {
            needUpdateOrgs = SpringBeanUtil.getBean(HttpYunHuInfoSync.class).getNeedUpdateOrgs(yunHuOrgList);
            log.info("需要新增机构数据量：{}", needUpdateOrgs.size());
            batchUpdateYunHuOrg(needUpdateOrgs);
        } catch (Exception e) {
            log.error("云湖数据落库失败", e);
            failureHandle();
            return;
        }
        List<OrgDO> orgDOList;
        try {
            orgDOList = SpringBeanUtil.getBean(HttpYunHuInfoSync.class).yunHuOrgConvert(needUpdateOrgs);
            log.info("云湖机构转换后：{}", orgDOList.size());
        } catch (Exception e) {
            log.error("机构转换失败", e);
            failureHandle();
            return;
        }
        try {
            List<List<OrgDO>> partition = Lists.partition(orgDOList, 200);
            for (List<OrgDO> orgDOS : partition) {
                batchUpdateOrg(orgDOS);
                log.info("机构入库成功记录数：{}", orgDOS.size());
            }
        } catch (Exception e) {
            log.error("机构落库失败",e);
            failureHandle();
        }
    }

    /**
     * 批量落库
     * @param orgDOList
     */
    private void batchUpdateOrg(List<OrgDO> orgDOList) {
        if (ObjectUtil.isEmpty(orgDOList)){
            log.info("没有需要落库的机构数据" );
            return;
        }
        List<String> orgCodes = orgDOList.stream().map(OrgDO::getCode).collect(Collectors.toList());
        List<OrgDO> orgDOS = SpringBeanUtil.getBean(OrgDOMapper.class).selectByExample(Example.builder(OrgDO.class).andWhere(Sqls.custom().andIn("code", orgCodes)).build());
        log.info("已存在机构表数据：{}条", orgDOS.size());
        if (ObjectUtil.isNotEmpty(orgDOS)){
            List<String> existCodes = orgDOS.stream().map(OrgDO::getCode).collect(Collectors.toList());
            orgDOList = orgDOList.stream().filter(item->!existCodes.contains(item.getCode())).collect(Collectors.toList());
            log.info("过滤已存在机构欧后，待新增机构数：{}条", orgDOList.size());
        }
        SpringBeanUtil.getBean(OrgDOMapper.class).batchInser(orgDOList);
        log.info("{}：更新机构数：{}", DateUtil.now(),orgDOList.size());
    }

    /**
     * 批量更新云湖机构表数据
     * @param yunHuOrgs
     */
    private void batchUpdateYunHuOrg(List<YunHuOrg> yunHuOrgs) {
        List<String> orgIds = yunHuOrgs.stream().map(YunHuOrg::getOrgId).collect(Collectors.toList());
        List<List<String>> orgIdsList
                = Lists.partition(orgIds, 200);
        for (List<String> strings : orgIdsList) {
            SpringBeanUtil.getBean(YunHuOrgMapper.class).batchDeleteByPrimaryKeys(strings);
        }
        List<List<YunHuOrg>> partition = Lists.partition(yunHuOrgs, 200);
        for (List<YunHuOrg> huOrgs : partition) {
            SpringBeanUtil.getBean(YunHuOrgMapper.class).batchSave(huOrgs);
        }
    }

    public void failureHandle(){
        log.info("同步失败机构落库待后续处理,同步失败用户集合：{}",yunHuOrgList.stream().map(YunHuOrg::getOrgId));
    }
}
